package com.platform.service;

import com.platform.cache.J2CacheUtils;
import com.platform.entity.TemplateMsgRequest;
import com.platform.utils.ResourceUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.net.URI;
import java.util.HashMap;
import java.util.Map;

@Service
public class WeixinService {
	
	@Autowired
	private RestTemplate restTemplate;

	@Autowired
	@Lazy
	private WeixinService weixinService;
	
	private Logger log = LoggerFactory.getLogger(getClass());

	public String token() {
		Object val = J2CacheUtils.get("weixinToken");
		if (val != null) {
			//return String.valueOf(val);
		}
		URI uri = UriComponentsBuilder.fromHttpUrl(
			"https://api.weixin.qq.com/cgi-bin/token")
			.queryParam("grant_type", "client_credential")
			.queryParam("appid", ResourceUtil.getConfigByName("wx.appId"))
			.queryParam("secret", ResourceUtil.getConfigByName("wx.secret"))
			.build().toUri();
		Map<String, Object> r = restTemplate.getForEntity(uri, 
			Map.class).getBody();
		String token = String.valueOf(r.get("access_token"));
		J2CacheUtils.put("weixinToken", token);

		return token;
	}

	/**
	 * 发送模板消息
	 * @return
	 */
	public void sendMsg(TemplateMsgRequest req, String formId) {
		log.info("formId:" + formId);
		URI uri = UriComponentsBuilder.fromHttpUrl(
				"https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send")
				.queryParam("access_token", weixinService.token())
				.build().toUri();
		//https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN
		Map<String, Object> msg = new HashMap<>();
		msg.put("touser", req.getOpenId());
		msg.put("template_id", req.getTemplateId());
		msg.put("data", req.getMsg());
		msg.put("url", req.getUrl());
		msg.put("form_id", formId);
		msg.put("page","pages/index/index");
		ResponseEntity resp = restTemplate.postForEntity(uri,
			new HttpEntity<Map<String, Object>>(msg), String.class);
		System.out.println(resp);
	}

}
